import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class UserDetails extends HttpServlet{
	public void init(ServletConfig config) throws ServletException{
		super.init(config);
		
	}
	//process HTTP Get request
	public void post(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException{
		String connectionURL="jdbc:derby://localhost:1527/APS_DB";
		Connection connection=null;
		ResultSet rs;
		res.setContentType("text/html");
		PrintWriter out=res.getWriter();
		
		//get data entered on the form
		String userID=req.getParameter("userID");
	    String surname=req.getParameter("surname");
	    String firstname=req.getParameter("firstname");
	    String email=req.getParameter("email");
	    String id=req.getParameter("passport");
	    String telephone=req.getParameter("telephone");
	    String dob=req.getParameter("dob");
	    String username=req.getParameter("username");
	    String password=req.getParameter("password");
	    String confpaswd=req.getParameter("confirm pswd");
	    
	    try {
	    	//load the database driver
	    	Class.forName("org.apache.derby.jdbc.ClientDriver");
	    	//get connection to the database
	    	connection=DriverManager.getConnection(connectionURL, "admin","secret");
	    	//add the data into the database
	    	String sql="insert into users values(?,?,?,?,?,?,?,?)";
	    	PreparedStatement pst=connection.prepareStatement(sql);
	    	pst.setString(1,userID);
	    	pst.setString(2,surname);
	    	pst.setString(3,firstname);
	    	pst.setString(4, email);
	    	pst.setString(5, id);
	    	pst.setString(6, telephone);
	    	pst.setString(7, dob);
	    	pst.setString(8,username);
	    	pst.setString(9, password);
	    	pst.setString(10,confpaswd);
	    	
	    	int numRowsChanged=pst.executeUpdate();
	    	
	    	//show that new account has been created
	    	out.println(firstname+" "+ "added");
	    	pst.close();
	    }
	    catch(ClassNotFoundException e){
	    	out.println("Could not load database driver: "+ e.getMessage());
	    }
	    catch(SQLException e){
	    	out.println("SQLException caught: "+e.getMessage());
	    }
	    catch(Exception e){
	    	out.println(e);
	    }
	    finally{
	    	try {
	    		if(connection!=null)
	    			connection.close();//close connection
	    	}
	    	catch (SQLException ignored){
	    		out.println(ignored);
	    	}
	    }
	}
	

}
